//获取权限方法
var userInfo = getAuthority();

var powerlist = JSON.parse(userInfo).permissions;
/*自定义函数判断权限*/
template.defaults.imports.hasPower = function(data){
    if(powerlist.includes(data)){
        return true;
    }
    return true;
};

layui.use(['layer', 'form', 'table', 'util', 'dtree','laypage','laydate','layedit'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var admin = layui.admin;
    var table = layui.table;
    var laydate = layui.laydate;
    var layedit = layui.layedit;
    var util = layui.util;
    var dtree = layui.dtree;
    var laypage = layui.laypage;
    var layer_popup = false;//控制删除弹窗时不会出现编辑弹窗的状态

    var Authorization;//请求接口用
    var count = 0;//总个数
    var current=1;//当前页
    var fistRenderPage= true;//是否第一次渲染分页
    var regionCatalogType = [];//区划配置类型

    if(userInfo){
        var access_token = localStorage.getExpire("access_token");
        var token_type = localStorage.getExpire("token_type");
        Authorization = token_type+" "+access_token;

        getRegionSetPower();
        getTemplateIdenManageTablePower();
        getRegionCatalogType(function () {
            getCatalogData();
        });
    }


    // 添加
    $('#add-btn-template-idenManage').click(function () {
        showAddModel();
    });

    // 工具条点击事件
    table.on('tool(regionsettable)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'edit') { // 修改
            layer_popup = true;
            showEditModel(data);
        } else if (layEvent === 'delete') { // 删除
            doDel(data);
            layer_popup = true;
        }else if(layEvent ==='updateOrigin'){//更新原点区划
            updateOrigin(data);
            layer_popup = true;
        }else if(layEvent ==='updateLastLog'){//更新上次版本
            updateLastLog(data);
            layer_popup = true;
        }

    });

    //监听行单击事件
    table.on('row(regionsettable)', function(obj){
        if(!layer_popup){
            showRegionManageModel(obj.data);
        }
    });

    function getRegionSetPower() {
        var str = template("regionset-tmpl",{});
        document.getElementById("regionset-tmpl-box").innerHTML = str;
    }

    /*获取区划配置类型*/
    function getRegionCatalogType(callback) {
        axios.get(regionUrl.catalog.regionCatalogType,{
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    regionCatalogType = response.data.data;
                    callback&&callback();
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }

    /*获取区划配置列表*/
    function getCatalogData(){
        var req={
            current: current,
            size: pageSize,
            flag:0
        };
        axios.get(regionUrl.catalog.catalogList,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    renderTable(data);
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }
    /*渲染表格*/
    function renderTable(data) {
        table.render({
            elem: '#regionsettable',
            size: 'sm', //小尺寸的表格
            page: false,
            cellMinWidth: 30,
            data:data.records,
            cols: [[
                {type:'numbers', title: '编号'},
                {field: 'name', align: 'center', title: '地图名称'},
                {field: 'year', align: 'center', title: '年份'},
                {field: 'regionType', align: 'center', title: '区划类型',templet: function(row){
                    for(var i in regionCatalogType){
                        if(regionCatalogType[i].value == row.regionType){
                            return regionCatalogType[i].type;
                        }
                    }
                }},
                {field: 'analysisService', align: 'center', title: '空间分析服务'},
                {field: 'dataService', align: 'center', title: '数据分析服务'},
                {field: 'queryService', align: 'center', title: '区划边界图层'},
                {field: 'tdlayerService', align: 'center', title: '二维图层服务'},
                {field: 'sdlayerService', align: 'center', title: '三维图层服务'},
                {field: 'utfGrid', align: 'center', title: '地图UTFGrid'},
                {field: 'dataPoint', align: 'center', title: '点数据'},
                {field: 'dataSet', align: 'center', title: '面数据'},
                {field: 'dataSource', align: 'center', title: '数据源'},
                {field: 'status', align: 'center', title: '状态',templet:function (row) {
                    let status = regionUrl.config.status;
                    for(var i in status){
                        if(status[i].value == row.status){
                            return status[i].name;
                        }
                    }
                }},
                {field: 'memo', align: 'center', title: '描述'},
                {align: 'center', toolbar: '#ident-template-idenManage-box', title: '操作', minWidth: 300}
            ]]
        });

        if(fistRenderPage){
            laypage.render({
                elem: 'page-box'
                ,count: data.total,
                limit:pageSize,
                groups:1,
                current:current
                ,layout: ['count','prev','page', 'next']
                ,jump: function(obj, first){
                    if(!first){
                        current = obj.curr;
                        fistRenderPage = false;
                        getCatalogData();
                    }
                }
            });
        }

    }
    /*渲染表格里的权限*/
    function getTemplateIdenManageTablePower() {
        var str = template("ident-template-idenManage-tmp",{});
        document.getElementById("ident-template-idenManage-box").innerHTML = str;
    }
    // 删除
    function doDel(obj) {
        layer.confirm('确定要删除行政区划“' + obj.name + '”吗？', {
            skin: 'layui-layer-admin',
            shade: .1,
            cancel: function(index, layero){
                layer_popup = false;//取消操作，点击右上角的X去掉弹窗限制
            }
        }, function (i) {
            layer.close(i);
            layer.load(2);
            axios({
                method: 'delete',
                url:regionUrl.catalog.deleteCatalog+obj.id,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        layer.closeAll('loading');
                        layer.msg("成功删除", {icon: 1});
                        getCatalogData();
                        fistRenderPage = true;
                        layer_popup = false;
                    } else {
                        layer.msg(res.data.message, {icon: 2});
                        layer.closeAll('loading');
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                })
        },function(){
            layer_popup = false;//点击取消去掉弹窗限制
        });
    }

    // 显示编辑表单弹窗
    function showEditModel(obj) {
        admin.open({
            type: 1,
            title: '修改行政区划类别',
            area: ['430px', '530px'],
            offset:'auto',
            content: $('#addClassifyForm').html(),
            end:function(){
                layer_popup = false;
            },
            success: function (layero, dIndex) {
                var regionCatalogTypeObj = {
                    list:regionCatalogType
                }
                var str = template("regionSetType-tmpl",regionCatalogTypeObj);
                document.getElementById("regionSetType").innerHTML = str;

                getAllSetVersion(function (versionList) {
                    var str = template("setVersionList-tmpl",versionList);
                    document.getElementById("setVersionListBox").innerHTML = str;
                    form.render('select'); //刷新select选择框渲染

                    form.val('addCatalogForm', obj);  // 回显数据
                });
                form.render('select'); //刷新select选择框渲染
                //年选择器
                laydate.render({
                    elem: '#test2'
                    ,type: 'year'
                });
                //监听开关
                form.render('checkbox');
                form.on('switch(autoplay)', function(){
                    ins3.reload({
                        autoplay: this.checked
                    });
                });


                form.on('submit(addCatalogSubmit)', function (data) {
                    var req = data.field;
                    req.id = obj.id;
                    req.version = obj.version;
                    req.sysTableName = obj.sysTableName;
                    if(data.field.status=="on"){
                        req.status = 1;
                    }else{
                        req.status = 0;
                    }
                    axios({
                        method: 'put',
                        url:regionUrl.catalog.editCatalog,
                        data:$.param(req),
                        headers:{
                            'Authorization':Authorization
                        }
                    })
                        .then(function (res) {
                            if (res.status == 200&&res.data.message=="success") {
                                layer.close(dIndex);
                                layer.closeAll('loading');
                                layer.msg(res.data.message, {icon: 1});
                                getCatalogData();
                            } else {
                                layer.closeAll('loading');
                                layer.msg(res.data.message, {icon: 2});
                            }
                        })
                        .catch(function (error) {
                            console.log(error);
                            if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                                // 进行重新登陆
                                localStorage.clear();
                                top.location.href=loginPageUrl;
                            }
                        })

                    return false;
                });

            }
        });
    }
    //添加弹窗
    function showAddModel() {
        admin.open({
            type: 1,
            title: '新建行政区划类别',
            area: ['430px', '530px'],
            offset:'auto',
            content: $('#addClassifyForm').html(),
            end:function(){
                layer_popup = false;
            },
            success: function (layero, dIndex) {
                var regionCatalogTypeObj = {
                    list:regionCatalogType
                }
                var str = template("regionSetType-tmpl",regionCatalogTypeObj);
                document.getElementById("regionSetType").innerHTML = str;

                getAllSetVersion(function (versionList) {
                    var str = template("setVersionList-tmpl",versionList);
                    document.getElementById("setVersionListBox").innerHTML = str;
                    form.render('select'); //刷新select选择框渲染
                });
                form.render('select'); //刷新select选择框渲染
                //年选择器
                laydate.render({
                    elem: '#test2'
                    ,type: 'year'
                });
                //监听开关
                form.render('checkbox');
                form.on('switch(autoplay)', function(){
                    ins3.reload({
                        autoplay: this.checked
                    });
                });

                form.on('submit(addCatalogSubmit)', function (data) {
                    var req = data.field;
                    req.regionType = Number(req.regionType);
                    req.id = "";
                    req.importType = "";
                    req.isImport = "";
                    req.isOrigin = 0;
                    req.sysTableName = "";
                    req.version = "";

                    if(data.field.status=="on"){
                        req.status = 1;
                    }else{
                        req.status = 0;
                    }
                    axios({
                        method: 'POST',
                        url:regionUrl.catalog.addCatalog,
                        data:$.param(req),
                        headers:{
                            'Authorization':Authorization
                        }
                    })
                        .then(function (response) {
                            if(response.status == 200 &&response.data.message == "success"){
                                layer.close(dIndex);
                                layer.closeAll('loading');
                                layer.msg(response.data.message, {icon: 1});
                                current = 1;
                                fistRenderPage = true;
                                getCatalogData();
                            }else{
                                layer.closeAll('loading');
                                layer.msg(response.data.message, {icon: 2});
                            }
                        })
                        .catch(function (error) {
                            console.log(error);
                            if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                                // 进行重新登陆
                                localStorage.clear();
                                top.location.href=loginPageUrl;
                            }
                        });

                    return false;
                });

            }
        });
    }

    // 获取所以配置版本
    function getAllSetVersion(callback){
        var req={
            current: 1,
            size: 100,
            flag:0
        };
        axios.get(regionUrl.catalog.catalogList,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    callback(data);
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }
    // 显示区划管理弹窗
    function showRegionManageModel(obj) {
        window.regionSelectedCatalog = obj;
        admin.popupRight({
            title: false, //不显示标题栏
            url: 'regionManage.html',
            offset: 'rt',
            area:['94vw;','calc(100vh - 30px)'],
            closeBtn: true,
            end: function () {
                getCatalogData();
            },
            success: function (layero, dIndex) {
                // 弹窗超出范围不出现滚动条
                $(layero).children('.layui-layer-content').css('overflow', 'visible');
            }
        });

    }

    //更新原点区划
    function updateOrigin(obj) {
        layer.load(2);
        let req = {
            rcid:obj.id
        }
        axios({
            method: 'put',
            url:regionUrl.info.updateOrigin,
            data:$.param(req),
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (res) {
                if (res.status == 200&&res.data.message=="success") {
                    layer.closeAll('loading');
                    layer.msg(res.data.message, {icon: 1});
                    getCatalogData();
                    layer_popup = false;
                } else {
                    layer.closeAll('loading');
                    layer.msg(res.data.message, {icon: 2});
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            })
    }

    //更新上次版本
    function updateLastLog(obj) {
        if(obj.lrcid){
            layer.load(2);
            let req = {
                id :obj.id,
                lrcid:obj.lrcid
            }
            axios({
                method: 'put',
                url:regionUrl.catalog.updateLastLog,
                data:$.param(req),
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        layer.closeAll('loading');
                        layer.msg(res.data.message, {icon: 1});
                        getCatalogData();
                        layer_popup = false;
                    } else {
                        layer.closeAll('loading');
                        layer.msg(res.data.message, {icon: 2});
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                })
        }else{
            layer.msg('没有上次版本', {icon: 2});
        }

    }
});







